<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑名片</title>
    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <meta name="viewport"
          content="initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,width=device-width"/>
    <meta name="format-detection" content="telephone=no"/>
    <meta name="app-mobile-web-app-capable" content="yes"/>
    <meta name="app-mobile-web-app-status-bar-style" content="black-translucent"/>
    <link rel="stylesheet" href="//at.alicdn.com/t/font_772560_3zni9tnu80h.css">
    <link rel="stylesheet" href="css/cropper.min.css">
    <link rel="stylesheet" href="css/edit-card.css">
    <script src="js/jquery.min.js"></script>
</head>
<body>
<form id='submitform'>
<div class="update-hdpic bg-white" id="replaceImg">
    <div class="flex flex-between align">
        <div class="hdpic-box">
            <img src="" alt="" id="finalImg">
        </div>
        <div class="update-rt flex align">
            <span>修改名片头像</span>
            <i class="ra ra-icon1"></i>
        </div>
    </div>
    <!--<input type="file" name="headPic" accept="image/png,jpg,jpge" id="picture" value="">-->
</div>
<div class="bg-white card-type">
    <div class="card-type-hd border-bottom1">选择名片头像类型</div>
    <div class="card-type-bd" id="choose-type">
        <div class="flex">
            <div class="type-item active" data-type="1">
                <img src="https://pimg.ec51.com/card/card-type1.png" alt="">
                <i class="ra ra-jiaobiao1"></i>
            </div>
            <div class="type-item" data-type="2">
                <img src="https://pimg.ec51.com/card/card-type2.png" alt="">
                <i class="ra ra-jiaobiao1"></i>
            </div>
        </div>
    </div>
</div>
<div class="input-section bg-white">
    <div class="input-item flex align">
        <label for="name">姓名</label>
        <div class="input-box">
            <input type="text" name="name" value="" required oninvalid="this.setCustomValidity('姓名不能为空');" oninput="setCustomValidity('')">
        </div>
    </div>
    <div class="input-item flex align">
        <label for="job">职位</label>
        <div class="input-box">
            <input type="text" name="job" value="" required oninvalid="this.setCustomValidity('职位不能为空');" oninput="setCustomValidity('')">
        </div>
    </div>
    <div class="input-item flex align">
        <label for="phone">手机号</label>
        <div class="input-box">
            <input type="text" name="phone" value="" pattern="^1[0-9]{10}$" required oninvalid="this.setCustomValidity('请输入正确的手机号码');" oninput="setCustomValidity('')">
        </div>
    </div>
</div>
<div class="input-section bg-white">
    <div class="input-item flex align">
        <label for="tel">电话</label>
        <div class="input-box">
            <input type="text" name="tel" value="">
        </div>
    </div>
    <div class="input-item flex align">
        <label for="email">邮箱</label>
        <div class="input-box">
            <input type="text" name="email" value=""  pattern="^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$" oninvalid="this.setCustomValidity('请输入正确的邮箱');" oninput="setCustomValidity('')">
        </div>
    </div>
    <div class="input-item flex align">
        <label for="wechat">微信</label>
        <div class="input-box">
            <input type="text" name="wechat" value="">
        </div>
    </div>
    <div class="input-item flex align">
        <label for="address">地址</label>
        <div class="input-box">
            <input type="text" name="address" value="">
        </div>
    </div>
</div>
    <input type="submit" value="保存" class="submit">
    <!--<button class="submit" type="submit">保存</button>-->
</form>
<!--图片裁剪框 start-->
<div style="display: none" class="tailoring-container">
    <div class="black-cloth" onclick="closeTailor(this)"></div>
    <div class="tailoring-content">
        <div class="tailoring-content-one">
            <label title="上传图片" for="chooseImg" class="l-btn choose-btn">
                <input type="file" accept="image/jpg,image/jpeg,image/png" name="file" id="chooseImg" class="hidden" onchange="selectImg(this)">
                选择图片
            </label>
            <div class="close-tailoring" onclick="closeTailor(this)">×</div>
        </div>
        <div class="tailoring-content-two">
            <div class="tailoring-box-parcel">
                <img id="tailoringImg">
            </div>
        </div>
        <div class="tailoring-content-three">
            <button class="l-btn cropper-reset-btn">复位</button>
            <button class="l-btn cropper-rotate-btn">旋转</button>
            <button class="l-btn cropper-scaleX-btn">换向</button>
            <button class="l-btn sureCut" id="sureCut">确定</button>
        </div>
    </div>
</div>
<!--图片裁剪框 end-->
<script src="js/cropper.min.js"></script>
<script src="https://cdn.staticfile.org/Plupload/2.1.1/moxie.js"></script>
<script src="https://cdn.staticfile.org/Plupload/2.1.1/plupload.dev.js"></script>
<script src="https://cdn.staticfile.org/qiniu-js-sdk/1.0.14-beta/qiniu.js"></script>
<script>
    let qiniuUrl = 'https://pimg.ec51.com/', token = '',keyUrl = '';
    $.ajax({
        url: 'https://qyim.ec51.com/v1/check/qiniu-token',
        async: false,
        success: res => {
            token = res.data
        },
        error:err=>{
            alert('获取token失败')
        }
    });
    //弹出图片裁剪框
    $("#replaceImg").on("click", function () {
        $(".tailoring-container").toggle();
    });

    //图像上传
    function selectImg(file) {
        if (!file.files || !file.files[0]) {
            return;
        }
        var fileMaxSize = 5 * 1024;//1M

        var reader = new FileReader();
        reader.onload = function (evt) {
            var replaceSrc = evt.target.result;
            //更换cropper的图片
            $('#tailoringImg').cropper('replace', replaceSrc, false);//默认false，适应高度，不失真
        }
        reader.readAsDataURL(file.files[0]);
    }

    //cropper图片裁剪
    $('#tailoringImg').cropper({
        aspectRatio: 1 / 1,//默认比例
        preview: '.previewImg',//预览视图
        guides: false,  //裁剪框的虚线(九宫格)
        autoCropArea: 0.8,  //0-1之间的数值，定义自动剪裁区域的大小，默认0.8
        dragCrop: false,  //是否允许移除当前的剪裁框，并通过拖动来新建一个剪裁框区域
        movable: true,  //是否允许移动剪裁框
        resizable: true,  //是否允许改变裁剪框的大小
        zoomable: true,  //是否允许缩放图片大小
        mouseWheelZoom: false,  //是否允许通过鼠标滚轮来缩放图片
        touchDragZoom: true,  //是否允许通过触摸移动来缩放图片
        rotatable: true,  //是否允许旋转图片
        viewMode:1,//0：没有限制，3可以移动到2外。  1 : 3只能在2内移动。  2：2图片 不全部铺满1 （即缩小时可以有一边出现空隙） 3：2图片填充整个1
        crop: function (e) {
            // 输出结果数据裁剪图像。
        }
    });
    //旋转
    $(".cropper-rotate-btn").on("click", function () {
        $('#tailoringImg').cropper("rotate", 45);
    });
    //复位
    $(".cropper-reset-btn").on("click", function () {
        $('#tailoringImg').cropper("reset");
    });
    //换向
    var flagX = true;
    $(".cropper-scaleX-btn").on("click", function () {
        if (flagX) {
            $('#tailoringImg').cropper("scaleX", -1);
            flagX = false;
        } else {
            $('#tailoringImg').cropper("scaleX", 1);
            flagX = true;
        }
        flagX != flagX;
    });

    //关闭裁剪框
    function closeTailor() {
        $(".tailoring-container").toggle();
    }

    //裁剪后的处理
    var base64url
    $("#sureCut").on("click", function () {
        if ($("#tailoringImg").attr("src") == null) {
            return false;
        } else {
            var cas = $('#tailoringImg').cropper('getCroppedCanvas');//获取被裁剪后的canvas
            base64url = cas.toDataURL('image/png'); //转换为base64地址形式
            // $("#finalImg").prop("src", base64url);//显示为图片的形式


            ImgToBase64(convertBase64ToBlob(base64url), 720, function (base64) {
                $("#finalImg").prop("src",base64);
                //上传到七牛云
                putb64(base64)

            });

            //关闭裁剪框
            closeTailor();
        }
    });
    function convertBase64ToBlob(base64){
        var base64Arr = base64.split(',');
        var imgtype = '';
        var base64String = '';
        if(base64Arr.length > 1){
            //如果是图片base64，去掉头信息
            base64String = base64Arr[1];
            imgtype = base64Arr[0].substring(base64Arr[0].indexOf(':')+1,base64Arr[0].indexOf(';'));
        }
        // 将base64解码
        var bytes = atob(base64String);
        //var bytes = base64;
        var bytesCode = new ArrayBuffer(bytes.length);
        // 转换为类型化数组
        var byteArray = new Uint8Array(bytesCode);

        // 将base64转换为ascii码
        for (var i = 0; i < bytes.length; i++) {
            byteArray[i] = bytes.charCodeAt(i);
        }

        // 生成Blob对象（文件对象）
        return new Blob( [bytesCode] , {type : imgtype});
    };

    function ImgToBase64(file, maxLen, callBack) {
        var img = new Image();

        var reader = new FileReader();//读取客户端上的文件
        reader.onload = function () {
            var url = reader.result;//读取到的文件内容.这个属性只在读取操作完成之后才有效,并且数据的格式取决于读取操作是由哪个方法发起的.所以必须使用reader.onload，
            img.src = url;//reader读取的文件内容是base64,利用这个url就能实现上传前预览图片
        };

        img.onload = function () {
            //生成比例
            var width = img.width, height = img.height;
            //计算缩放比例
            var rate = 1;
            if (width >= height) {
                if (width > maxLen) {
                    rate = maxLen / width;
                }
            } else {
                if (height > maxLen) {
                    rate = maxLen / height;
                }
            };

            img.width = width * rate;
            img.height = height * rate;
            //生成canvas
            var canvas = document.createElement("canvas");
            var ctx = canvas.getContext("2d");
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0, img.width, img.height);
            var base64 = canvas.toDataURL('image/jpeg', getCompressRate(1,showSize(base64url)));
            callBack(base64);
        };
        reader.readAsDataURL(file);
    }


    //计算压缩比
    function getCompressRate(allowMaxSize,fileSize){ //计算压缩比率，size单位为MB
        var compressRate = 1;
        if(fileSize/allowMaxSize > 4){
            compressRate = 0.5;
        } else if(fileSize/allowMaxSize >3){
            compressRate = 0.6;
        } else if(fileSize/allowMaxSize >2){
            compressRate = 0.7;
        } else if(fileSize > allowMaxSize){
            compressRate = 0.8;
        } else{
            compressRate = 0.9;
        }
        result6 = compressRate;
        return compressRate;
    }

    function showSize(base64url) {
        //获取base64图片大小，返回MB数字
        var str = base64url.replace('data:image/png;base64,', '');

        var equalIndex = str.indexOf('=');
        if(str.indexOf('=')>0) {
            str=str.substring(0, equalIndex);
        }
        var strLength=str.length;

        var fileLength=parseInt(strLength-(strLength/8)*2);
        // 由字节转换为MB
        var size = "";
        size = (fileLength/(1024 * 1024)).toFixed(2);
        var sizeStr = size + "";                        //转成字符串
        var index = sizeStr.indexOf(".");                    //获取小数点处的索引
        var dou = sizeStr.substr(index + 1 ,2)            //获取小数点后两位的值
        if(dou == "00"){                                //判断后两位是否为00，如果是则删除00
            return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
        }
        return parseInt(size);
    }


    function putb64(base64url){
        var pic = base64url.replace(/^.*?,/,'')
        var url = "https://upload.qiniup.com/putb64/-1";
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange=function(){
            if (xhr.readyState == 4) {
                if(xhr.status==200){
                    var keyText = xhr.responseText;
                    keyText=JSON.parse(keyText)
                    keyUrl = qiniuUrl+keyText.key;
                    console.log(keyUrl,'keyurlxxxxxxxxxxxxx')
                }else{
                    // 失败，根据响应码判断失败原因:
                    return alert(request.status);
                }
            }else{

            }
        };
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/octet-stream");
        xhr.setRequestHeader("Authorization", "UpToken " + token);
        xhr.send(pic);
    }
</script>
<script>
    let id = sessionStorage.getItem('login_identifier') , cardType = 1;
    $(document).ready(function () {
        $.ajax({
            url: 'https://qyim.ec51.com/v1/check/detail?type=1',
            method: 'post',
            data: {
                id: id
            },
            datatype: 'json',
            success: function (res) {
                var type = res.data.card_mode_type == 1
                $('#choose-type').find('.type-item').eq(type == 1 ? 0 : type == 2 ? 1 : 0).addClass('active').siblings().removeClass('active');
                $("#finalImg").attr('src', res.data.card_background);
                $("input[name='name']").val(res.data.name);
                $("input[name='job']").val(res.data.position);
                $("input[name='phone']").val(res.data.mobile);
                $("input[name='tel']").val(res.data.telephone_number);
                $("input[name='email']").val(res.data.email);
                $("input[name='wechat']").val(res.data.wx_number);
                $("input[name='address']").val(res.data.address);
            }
        })
    });
    $('#choose-type').find('.type-item').bind('click', function () {
        cardType = $(this).attr('data-type');
        $(this).addClass('active').siblings().removeClass('active');
    });
    $("#submitform").on("submit", function(ev) {
        $("body").append("<div class=\"loadingWrap\"></div>");
        var name =  $("input[name='name']").val();
        var phone = $("input[name='phone']").val();
        var position = $("input[name='job']").val();
        var tel = $("input[name='tel']").val();
        var email = $("input[name='email']").val();
        var wechat =  $("input[name='wechat']").val();
        var address = $("input[name='address']").val();
        var data = {
            id: id,
            card_background: keyUrl,
            card_mode_type: cardType,
            name:name,
            position: position,
            mobile: phone,
            telephone_number: tel,
            email: email,
            wx_number: wechat,
            address: address
        };
        $.ajax({
            url: 'https://qyim.ec51.com/v1/check/detail?type=2',
            method: 'post',
            data: data,
            success: res => {
                if(res.data == true){
                    $('.loadingWrap').remove();
                    alert('修改成功');
                    window.location.href = "mine.html";
                }
                else{
                    alert(res.data);
                }
                return
            },
        })
        ev.preventDefault()
    })


</script>

</body>
</html>